package cn.iocoder.yudao.boot.common.exception;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.http.HttpStatus;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

/**
 * 错误码对象
 * <p>
 */
@Data
@AllArgsConstructor
public class ResultCode {
    private final HttpStatus httpStatus;
    private final String code;
    private final String msg;

    public ResultCode(HttpStatus httpStatus, ErrorCode errorCode) {
        this.httpStatus = httpStatus;
        this.code = getCodes(errorCode);
        this.msg = errorCode.getMsg();
    }

    private String getCodes(ErrorCode errorCode) {
        List<String> codes = new ArrayList<>();
        handler(codes, errorCode);
        StringJoiner strJoi = new StringJoiner(".");
        for (int i = codes.size() - 1; i >= 0; i--) {
            strJoi.add(codes.get(i));
        }
        return strJoi.toString();
    }

    private void handler(List<String> codes, ErrorCode errorCode) {
        codes.add(errorCode.getCode());
        ErrorCode parent = errorCode.getParent();
        if (parent != null) {
            handler(codes, parent);
        }
    }
}
